/* 提供一些公用方法 */
import Vue from 'vue';
import { Dialog, Toast } from 'vant';

Vue.use(Dialog);
Vue.use(Toast);

/* 页面标题切换 */
const setDocumentTitle = (title) => {
  document.title = title;
  // 通过创建iframe，动态更新title值
  const i = document.createElement('iframe');
  i.src = '';
  i.style.display = 'none';
  i.onload = function () {
    setTimeout(() => {
      i.remove();
    }, 9);
  };
  document.body.appendChild(i);
};

// 获取地址栏所带的参数
const getUrlParam = (name) => {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  const r = window.location.search.substr(1).match(reg);
  if (r != null) { return decodeURIComponent(r[2]); }
  return null;
};

/* 存储信息到sessionStorage */
const setStorage = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.sessionStorage.setItem(name, content);
};

/* 获取sessionStorage信息 */
const getStorage = name => {
  if (!name) return;
  try {
    return JSON.parse(window.sessionStorage.getItem(name));
  } catch (e) {
    return window.sessionStorage.getItem(name);
  }
};

/* 删除sessionStorage信息 */
const removeStorage = name => {
  if (!name) return;
  window.sessionStorage.removeItem(name);
};

/**
 * 重新封装iConfirm方法
 * @param {string} title 必传
 * @param {string} info 必传
 * @param {string} btnText1 非必传，默认'确定'
 * @param {string} btnText2 非必传，默认'取消'
 * @param {string} className 非必传，设置特殊样式
 * 尽量btnText1,btnText2同时设置，func1,func2同时设置
 */
const iConfirm = (title, info, btnText1, btnText2, func1, func2, className = '') => {
  // title参数不可省略，至少输入两个参数title,info
  if (typeof btnText1 === 'string') {
    if (func1 == null) {
      func1 = function () {};
    }
    if (func2 == null) {
      func2 = function () {};
    }
  } else if (typeof btnText1 === 'function') {
    if (btnText2 != null) {
      func2 = btnText2;
    }
    func1 = btnText1;
    btnText1 = '';
    btnText2 = '';
  } else if (btnText1 == null) {
    btnText1 = '';
    btnText2 = '';
    func1 = function () {};
    func2 = function () {};
  }

  Dialog.confirm({
    title: title || '提示',
    message: info,
    messageAlign: 'left',
    className,
    confirmButtonText: btnText1 || '确定',
    cancelButtonText: btnText2 || '取消',
    beforeClose: (action, done) => {
      // 每次打开弹窗,内容置顶
      const vanDialog = document.getElementsByClassName('van-dialog__message');
      vanDialog[0] && (vanDialog[0].scrollTop = 0);
      done();
    }
  }).then(() => {
    func1();
  }).catch(() => {
    func2();
  });
};

/**
 * 重新封装iAlert方法
 * @param {string} title 必传
 * @param {string} info 必传
 * @param {string} btnText 非必传，默认'确定'
 * @param {string} className 非必传，设置特殊样式
 */
const iAlert = (title, info, btnText, funcHide, funcShow, className = '') => {
  // title参数不可省略，至少输入两个参数title,info
  if (typeof btnText === 'string') {
    if (funcHide == null) {
      funcHide = function () {};
    }
    if (funcShow == null) {
      funcShow = function () {};
    }
  } else if (typeof btnText === 'function') {
    if (funcHide != null) {
      funcShow = funcHide;
    } else {
      funcShow = function () {};
    }
    // 先判读funcHide是否存在，再重置；
    funcHide = btnText;
    btnText = '';
  } else if (btnText == null) {
    btnText = '';
    funcHide = function () {};
    funcShow = function () {};
  }

  Dialog.alert({
    title: title || '提示',
    message: info,
    messageAlign: 'left',
    className,
    confirmButtonText: btnText || '确定'
  }).then(() => {
    funcHide();
  });
};

/**
 * 重新封装iDialog方法
 * @param {string} title 必传
 * @param {string} info 必传
 * 针对只有一两句话，且文字居中展示的情况
 */
const iDialog = (title, info) => {
  Dialog({
    title,
    message: info
  });
};

/* 重新封装iToast方法 */
const iToast = (text, position, type) => {
  Toast(text);
};

// 构造顺序数组，如[1,2,3,4]
const newArray = (start, end) => {
  return Array.apply([], Array(end - start + 1)).map((item, index) => start + index);
};

// 高位补0
const prefixInteger = (num, length) => {
  return (Array(length).join('0') + num).slice(-length);
};

// 判断app版本号大于等于某特定版本号如5.0.7/5.0.7.1
const bigAppVersion = (version, thenVersion) => {
  const versions = version.split('.').map(Number);
  const thenVersions = thenVersion.split('.').map(Number);
  let flag = versions[0] > thenVersions[0]
    || (versions[0] == thenVersions[0] && versions[1] > thenVersions[1])
    || (versions[0] == thenVersions[0]
      && versions[1] == thenVersions[1]
      && versions[2] >= thenVersions[2]);
  if (flag && versions[2] == thenVersions[2]) {
    if (versions.length == 3 && thenVersions.length == 4) {
      flag = false;
    }
    if (versions.length == 4 && thenVersions.length == 4) {
      flag = versions[3] >= thenVersions[3];
    }
  }
  return flag;
};

// 用script标签，动态引入外部资源
const importScript = (obj) => {
  // 设置默认值
  obj = obj || {};
  obj.flag = obj.flag || 'flag';
  obj.url = obj.url || '/dz-mall/otc/front/lib/dgzq.ico';
  // 创建script标签，引入外部资源
  const head = document.getElementsByTagName('head')[0];
  const scripts = document.getElementsByTagName('script');
  for (let i = 0; i < scripts.length; i++) {
    // 已经引入了的，不再继续引入
    if (scripts[i].getAttribute(obj.flag)) {
      obj.callback && obj.callback();
      return false;
    }
  }
  const script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute(obj.flag, true);
  script.src = obj.url;
  head.appendChild(script);
  // script加载完/加载失败回调
  script.onload = () => {
    obj.callback && obj.callback();
  };
  script.onerror = () => {
    console.log('Script Load Error!');
  };
};

// 引导用户下载掌证宝app
const downLoadApp = () => {
  window.location.href = 'http://a.app.qq.com/o/simple.jsp?pkgname=dongzheng.szkingdom.android.phone';
};

export default {
  setDocumentTitle,
  getUrlParam,
  setStorage,
  getStorage,
  removeStorage,
  iConfirm,
  iAlert,
  iDialog,
  iToast,
  newArray,
  prefixInteger,
  bigAppVersion,
  importScript,
  downLoadApp
};
